package com.glodon.paas.search.mapping;

import java.io.InputStream;

import javax.annotation.PostConstruct;
import javax.ws.rs.core.MediaType;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.glodon.paas.search.util.SearchConstants;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;

@Component
public class InitMappingService {

    private static Logger logger = LoggerFactory.getLogger(InitMappingService.class);
    @Value("${api.internal.es.url}")
    private String esUrl;
    private String docMapping = "mapping/doc.json";
    private String rvtMapping = "mapping/rvt.json";

    @PostConstruct
    public void initMappings() throws Exception {
        initMapping(SearchConstants.INDEX_PAAS, SearchConstants.TYPE_DOC, docMapping);
        initMapping(SearchConstants.INDEX_PAAS, SearchConstants.TYPE_RVT, rvtMapping);
    }

    private void initMapping(String index, String type, String mappingUrl) throws Exception {
        StringBuilder url = new StringBuilder(esUrl.trim());
        url.append("/").append(index).append("/").append(type);
        WebResource resource = Client.create().resource(url.toString());
        int status = resource.type(MediaType.APPLICATION_JSON_TYPE).head().getStatus();
        if (status == 200) {// mapping存在，初始化完成
            logger.info("index[{}] type[{}] exist already.", index, type);
            return;
        }
        // mapping不存在
        resource = Client.create().resource(esUrl.trim() + "/" + index);
        status = resource.type(MediaType.APPLICATION_JSON_TYPE).head().getStatus();
        if (status == 404) {// index不存在，则先建index
            Client.create().resource(esUrl.trim() + "/" + index).put(ClientResponse.class).close();
        }

        String mapping = getMapping(mappingUrl);
        resource = Client.create().resource(url.append("/_mapping").toString());
        ClientResponse resp = resource.type(MediaType.APPLICATION_JSON_TYPE).put(ClientResponse.class, mapping);
        if (200 <= resp.getStatus() && resp.getStatus() <= 206) {
            logger.info("successful created index [{}] type [{}]", index, type);
            String result = resp.getEntity(String.class);
            logger.debug(result);
        } else {
            logger.error("failed to creating mapping:", resp);
        }
        resp.close();
    }

    public void setEsUrl(String esUrl) {
        this.esUrl = esUrl;
    }

    private String getMapping(String mappingUrl) throws Exception {
        InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(mappingUrl);
        String mapping = IOUtils.toString(is);
        return mapping;
    }
}
